package org.port.weather;

import java.util.ArrayList;

import org.port.R;
import org.port.contacts.ContactsActivity;
import org.port.database.DatabaseActivity;
import org.port.util.Log;
import org.port.util.Util;
import org.port.weather.data.WeatherData;
import org.port.weather.ui.AddressPopup;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

public class WeatherActivity extends Activity {
	public static final String TAG = "WeatherActivity";
	public static final String KMA_DEFAULT_ADDRESS = "http://www.kma.go.kr"; // 기상청
																				// 기본
																				// 주소
	private int DIALOG_LOG = 0x0001;

	/**
	 * @author yjWee BroadCast에 담는 액션 정의
	 */
	public enum WeatherAction {
		REQUEST_WEATHER_DATA, UPDATE_WEATHER_TABLE, APPWIDGET_UPDATE, APPWIDGET_ENABLE;
		public static WeatherAction toAction(String str) {
			Log.d(TAG, "WeatherAction toAction: " + str);
			return valueOf(str.toUpperCase());
		}
	}

	private ArrayList<WeatherData> weatherDataList = new ArrayList<WeatherData>(); // 시간대별
																					// 날씨
																					// 정보
	private Context mContext;
	private LinearLayout mLayout;
	private TextView mTxtTownName;
	private AppWidgetHost mAppWidgetHost; // 위젯
	private AddressPopup mAddrPopup; // 주소 선택 팝업
	private WeatherReceiver mRecevier;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weather);
		this.mContext = getApplicationContext();
		setAlarm();
		mAppWidgetHost = new AppWidgetHost(mContext, 0);
		mLayout = (LinearLayout) findViewById(R.id.layout_weather);
		mTxtTownName = (TextView) findViewById(R.id.txt_town_name);

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mAppWidgetHost.startListening();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mRecevier = new WeatherReceiver();
		String townName = Util.getPrefer(mContext).getString(Util.LAST_TOWN,
				getString(R.string.str_def_address));
		mTxtTownName.setText(townName);
		mLayout.removeAllViewsInLayout();
		weatherDataList.clear();
		mRecevier.parseWeatherList(
				Util.getPrefer(mContext).getString(Util.LAST_GRID,
						"/wid/queryDFS.jsp?gridx=61&gridy=125"),
				weatherDataList, mContext);
		addLayout();
		Util.printSignatures(mContext);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mAppWidgetHost.stopListening();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			int widgetId = data.getIntExtra(
					AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
			Log.i(TAG, "onActivityResult WidgetID: " + widgetId);
			AppWidgetProviderInfo info = AppWidgetManager.getInstance(mContext)
					.getAppWidgetInfo(widgetId);
			addAppWidget(widgetId, info);
		}
	}

	/*
	 * 위젯 상태를 1시간 마다 업데이트 하기 위한 함수
	 */
	private void setAlarm() {
		Intent intent = new Intent();
		intent.setAction(WeatherAction.REQUEST_WEATHER_DATA.toString());
		PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent, 0);
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
				AlarmManager.INTERVAL_HOUR, pi);
	}

	private void addAppWidget(int id, AppWidgetProviderInfo info) {
		AppWidgetHostView hostView = mAppWidgetHost.createView(mContext, id,
				info);
		mLayout.addView(hostView);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);
		TextView tv = new TextView(mContext);
		tv.setScrollContainer(true);
		tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		tv.setText(Util.fileRead(mContext, Util.FILE_NAME_LOG));
		dialog.addContentView(tv, new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		return builder.create();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.weather, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_new_location:
			showPopup();
			break;
		case R.id.menu_log:
			showDialog(DIALOG_LOG);
			break;
		case R.id.menu_create_file:
			Util.createLogFileToExternalStorage(mContext, Util.FILE_NAME_LOG);
			break;
		case R.id.menu_contacts:
			Intent i = new Intent(mContext, ContactsActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(i);
			break;
		case R.id.menu_database:
			startActivity(new Intent(mContext, DatabaseActivity.class));
			break;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onBackPressed()");
		if ((mAddrPopup != null) && mAddrPopup.isShowing()) {
			mAddrPopup.dismiss();
		} else {
			super.onBackPressed();
		}
	}

	/**
	 * 주소 선택 팝업
	 */
	private void showPopup() {
		View v = View.inflate(this, R.layout.weather_popup, null);
		v.setBackgroundColor(Color.argb(30, 255, 255, 255));
		Display display = Util.getDisplay(mContext);
		mAddrPopup = new AddressPopup(mContext, v, display.getWidth() / 2,
				LayoutParams.WRAP_CONTENT, false);
		mAddrPopup.showAsDropDown(v, display.getWidth() / 4,
				display.getHeight() / 3);
		mAddrPopup.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				/*
				 * 팝업을 확인 이벤트로 해제 시 Preferences에서 마지막에 저장된 도시의 이름을 가져온 뒤 데이터를
				 * 기상청에 요청 후 레이아웃을 변경해준다.
				 */
				if (mAddrPopup.isConfirm) {
					String townName = Util.getPrefer(mContext)
							.getString(Util.LAST_TOWN,
									getString(R.string.str_def_address));
					mTxtTownName.setText(townName);
					mLayout.removeAllViewsInLayout();
					weatherDataList.clear();
					mRecevier.parseWeatherList(mAddrPopup.getGridData(),
							weatherDataList, mContext);
					addLayout();
				}
			}
		});
	}

	public void addLayout() {
		Log.i(TAG, "addLayout List Count: " + weatherDataList.size());
		for (int i = 0; i < weatherDataList.size(); i++) {
			View v = View.inflate(mContext, R.layout.weather_item, null);
			TextView txtHour = (TextView) v.findViewById(R.id.txt_weather_hour);
			ImageView ivState = (ImageView) v
					.findViewById(R.id.iv_weather_state);
			TextView txtRain = (TextView) v.findViewById(R.id.txt_weather_rain);
			TextView txtTemp = (TextView) v.findViewById(R.id.txt_weather_temp);
			TextView txtWind = (TextView) v.findViewById(R.id.txt_weather_wind);
			WeatherData data = weatherDataList.get(i);
			txtHour.setText(data.getHour() + getString(R.string.str_hour));
			if ("눈/비".equals(data.getWfKor())) {
				Util.setKmaImg(ivState, "눈비");
			} else {
				Util.setKmaImg(ivState, data.getWfKor());
			}
			txtTemp.setText(data.getTemp() + getString(R.string.str_temp));
			if ("".equals(data.getS12())) {
				txtRain.setText(data.getR12() + getString(R.string.str_rain));
			} else {
				txtRain.setText(data.getS12() + getString(R.string.str_rain));
			}
			txtWind.setText(data.getWdKor()
					+ "\n"
					+ data.getWs().substring(0,
							data.getWs().indexOf(".", 0) + 2)
					+ getString(R.string.str_wind));
			v.setPadding(10, 0, 0, 0);
			mLayout.addView(v);
		}
	}

	/*
	 * 기상청 날씨 정보 태그
	 */
	enum Weather {
		HOUR, DAY, TEMP, TMX, TMN, SKY, PTY, WFKOR, WFEN, POP, R12, S12, WS, WD, WDKOR, WDEN, REH;
		public static Weather toString(String str) {
			return valueOf(str.toUpperCase());
		}
	}

}
